<?php
class Area extends AppModel {
	var $name = 'Area';	
	//var $actsAs = array('Tree');
	var $hasMany = array(
		'Child' => array(
			'className' => 'Area',
			'foreignKey' => 'padre_id'
		)         
	); 

	public function generateCodigo(){
		$area = $this->find('first', array(
					'fields'=>array('substring("Area"."codigo",3,6) AS "Area__codigo"'),
					'conditions'=>array('Area.empresa_id'=>$this->empresaId()),
					'order'=>array('Area.codigo'=>'desc')));
		if(empty($area)){
			return str_repeat('0',2-strlen($this->empresaId())).'000001';
		} else {
			$new_codigo = (int)$area['Area']['codigo']+1;	
			return str_repeat('0',6-strlen($new_codigo )).$new_codigo;
		}
	}
}
?>